package com.tao.lab.camera

import android.content.ContentValues
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Build
import android.provider.ContactsContract
import android.provider.MediaStore
import android.util.Log
import androidx.camera.core.*
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContextCompat
import androidx.lifecycle.LifecycleOwner
import com.tao.lab.utils.Single
import java.io.File

/**
 *
 * @ProjectName:    utry-avatar
 * @Package:        com.utry.avatar.part
 * @ClassName:      CameraControl
 * @Description:     java类作用描述
 * @Author:         wangxf
 * @CreateDate:     2022/6/16 13:48
 * @UpdateUser:     更新者
 * @UpdateDate:     2022/6/16 13:48
 * @UpdateRemark:   更新说明
 * @Version:        1.0
 */
interface CameraControl {

    fun initControl()
    fun startCamera(
        context: Context,
        surfaceProvider: Preview.SurfaceProvider,
        lifecycleOwner: LifecycleOwner
    )

    fun takePhoto(callback: (file: String) -> Unit)
    fun close()
}

class CameraControlImpl private constructor() : CameraControl {
    companion object : Single<CameraControlImpl>(::CameraControlImpl);


    lateinit var context: Context
    var cameraProvider: ProcessCameraProvider? = null;
    override fun initControl() {

    }

    var imageCapture: ImageCapture? = null;
    var imageAnalyzer: ImageAnalysis? = null;

    override fun startCamera(
        context: Context,
        surfaceProvider: Preview.SurfaceProvider,
        lifecycleOwner: LifecycleOwner
    ) {


        this.context = context;
//        var cameraProviderFuture = ProcessCameraProvider.appPathgetInstance(context)
//        cameraProviderFuture.addListener({
//            // Used to bind the lifecycle of cameras to the lifecycle owner
//            cameraProvider = cameraProviderFuture.get()
//
//
//            // Preview
//            val preview = Preview.Builder()
//                .build()
//                .also {
//                    it.setSurfaceProvider(surfaceProvider)
//                }
//
//            // Select back camera as a default
//            val cameraSelector = CameraSelector.DEFAULT_FRONT_CAMERA
//
//
//            // ImageCapture
//            imageCapture = ImageCapture.Builder()
//                .setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
//
//                .build();
//
//            // ImageAnalysis
//            imageAnalyzer = ImageAnalysis.Builder()
//
//                .build();
//
//            try {
//                // Unbind use cases before rebinding
//                cameraProvider?.unbindAll()
//
//                // Bind use cases to camera
//                cameraProvider?.bindToLifecycle(
//                    lifecycleOwner, cameraSelector, preview, imageCapture, imageAnalyzer
//                )
//
//            } catch (exc: Exception) {
//
//            }
//
//        }, ContextCompat.getMainExecutor(context))
    }

    var callback: ((file: String) -> Unit)? = null;
    override fun takePhoto(handle: (file: String) -> Unit) {
// Get a stable reference of the modifiable image capture use case
        this.callback = handle;
        val imageCapture = imageCapture ?: return

        // Create time stamped name and MediaStore entry.

        val contentValues = ContentValues().apply {
            put(MediaStore.MediaColumns.DISPLAY_NAME, System.currentTimeMillis())
            put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg")
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) {
                put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/CameraX-Image")
            }
        }

        val file = File(
            context.getExternalFilesDir(null)?.absolutePath,
            System.currentTimeMillis().toString() + ".jpg"
        )
        file.createNewFile()

        // Create output options object which contains file + metadata
        val outputOptions = ImageCapture.OutputFileOptions
            .Builder(
                file
            )
            .build()

        // Set up image capture listener, which is triggered after photo has
        // been taken
        imageCapture.takePicture(
            outputOptions,
            ContextCompat.getMainExecutor(context),
            object : ImageCapture.OnImageSavedCallback {
                override fun onError(exc: ImageCaptureException) {
                }

                override fun
                        onImageSaved(output: ImageCapture.OutputFileResults) {
                    val msg = "Photo capture succeeded: ${output.savedUri}"

                    Log.i("takePhoto", "onImageSaved:${file}")
                    callback?.let { it(file.absolutePath) }

                }
            }
        )
    }

    override fun close() {
        cameraProvider?.unbindAll()
        callback = null
    }


}